import {
  HOME_ROUTE_NAME,
  LOGIN_ROUTE_NAME,
  WHITE_LIST
} from '@/router/constants'
import router from '@/router'
import { isLogin } from '@/utils/auth'
import store from '@/store'
import { generateTitle } from '@/utils/i18n'

router.beforeEach(async (to, from, next) => {
  if (isLogin()) {
    // 如果没有用户信息，就请求一个用户信息
    if (!store.getters.hasUserInfo) {
      await store.dispatch('user/getUserInfo')
    }
    if (to.name === LOGIN_ROUTE_NAME) {
      next({ name: HOME_ROUTE_NAME })
    } else {
      next()
    }
  } else {
    if (WHITE_LIST.includes(to.name)) {
      next()
    } else {
      next({
        name: LOGIN_ROUTE_NAME
      })
    }
  }
})

router.afterEach((to) => {
  document.title =
    process.env.VUE_APP_TITLE +
    ' - ' +
    generateTitle('route.' + to.meta.title)()
})
